package com.duing.handler;

import com.duing.bean.DataBean;
import com.google.gson.Gson;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class JSoupHandler {

    private static String urlStr = "https://ncov.dxy.cn/ncovh5/view/pneumonia";

    //返回数据的方法
    public static List<DataBean> getData(){
        List<DataBean> dataBeans = new ArrayList<>();
        try {
            //获取链接地址
            Document doc = Jsoup.connect(urlStr).get();
            //获取需要解析的Script标签
            Element script = doc.getElementById("getAreaStat");
            //获取数据
            String data = script.data();
            //截取需要的json数据
            String subData = data.substring(data.indexOf("["),data.lastIndexOf("]")+1);

            //转换成json数据
            Gson gson = new Gson();
            ArrayList list = gson.fromJson(subData, ArrayList.class);

            //循环遍历
            for (int i = 0; i < list.size(); i++) {
                 // 遍历获取每次循环的到的数据
                 Map map = (Map)list.get(i);
                 String area = (String)map.get("provinceShortName");
                 double confirm = (Double)map.get("confirmedCount");
                 double nowConfirm = (Double)map.get("currentConfirmedCount");
                 double dead = (Double)map.get("deadCount");
                 double  heal = (Double)map.get("curedCount");
                 DataBean dataBean = new DataBean(0L,area,(int)confirm,(int)nowConfirm,(int)dead,(int)heal);
                 dataBeans.add(dataBean);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataBeans;
    }

    public static void main(String[] args){

//        String html = "<html><head><title>First parse</title></head><body><p>Parsed HTML into a doc.</p></body></html>";
//        Document doc = Jsoup.parse(html);
//        System.out.println(doc);

        getData();
    }
}
